package com.aki.ai_property.service.impl;

import com.aki.ai_property.config.SystemConfig;
import com.aki.ai_property.dao.UserDao;
import com.aki.ai_property.entity.User;
import com.aki.ai_property.service.intf.UserService;
import com.aki.ai_property.util.PassUtils;
import com.aki.ai_property.util.StringUtil;
import com.aki.ai_property.vo.PageBean;
import com.aki.ai_property.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PatchMapping;

import javax.servlet.http.HttpSession;
import java.util.Objects;

/**
 * ━━━━━━永无BUG!━━━━━━
 *
 * @author AKI
 * @date 2022/8/25
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao dao;

    /**
     * 注册管理
     *
     * @param user
     * @return
     */
    @Override
    public Result save(User user) {

        if (dao.selectByName(user.getUsername()) == null) {

            if (StringUtil.isNotEmpty(user.getUsername(), user.getPassword())) {
                //2.密码转为密文
                user.setPassword(PassUtils.aesenc(SystemConfig.PASS_KEY, user.getPassword()));
                //3.新增
                if (dao.save(user) > 0) {
                    //成功
                    return Result.ok();
                }
            }

        }
        return new Result(400, "FAIL", null);

    }

    /**
     * 登录
     *
     * @param user
     * @param session
     * @return
     */
    @Override
    public Result login(User user, HttpSession session) {
        //查询用户
        String u = user.getUsername();
        String u2 = user.getPassword();


        //1.校验参数
        if (StringUtil.isNotEmpty(u, u2)) {
            //2.查询数据库
            User u1 = dao.selectByName(u);

            //3.验证是否存在用户
            if (Objects.nonNull(u)) {

                //4.验证账号的有效性
                //验证密码
                if (Objects.equals(u1.getPassword(), PassUtils.aesenc(SystemConfig.PASS_KEY, u2))) {
                    //6.登录成功 存储到Session
                    session.setAttribute("user", u1);
                    //7.返回
                    return Result.ok();
                }
            }
        }
        //防止撞库
        return Result.fail("亲，账号或密码错误");
    }

    @Override
    public Result all() {
        return Result.ok(dao.all());
    }

    @Override
    public PageBean selectPage(String name, int page, int limit) {
        if (StringUtil.isNotEmpty(name)) {
            name = "%" + name + "%";
        }
        int start = (page - 1) * limit;
        return PageBean.ok(dao.selectCount(name), dao.selectPage1(name, start, limit));
    }




    @Override
    public Result delete(Integer id) {
        if (dao.delete(id) > 0) {
            return Result.ok();
        }
        return Result.fail();
    }
}
